'use strict'
exports.main = async (event) => {
  const tcb = require('@cloudbase/node-sdk')
  const app = tcb.init()
  const db = app.database()
  if (event.httpMethod != 'POST') {
    return {
      errCode: 1000,
      errMsg: '请求方法错误',
      errFix: '使用POST方法请求'
    }
  }
  try {
    const requestdata = JSON.parse(event.body)
    let keyword = db.command.neq(null)
    if (typeof (requestdata.keyword) == 'string' && requestdata.keyword) {
      keyword = db.RegExp({
        regexp: requestdata.keyword,
        options: 'i'
      })
    }
    let tag = db.command.neq(null)
    if (Array.isArray(requestdata.tag) && requestdata.tag.length > 0) {
      tag = db.command.all(requestdata.tag)
    }
    const resourceres = await db.collection('resource').where({
      name: keyword,
      releaseStatus: 'release',
      searchTag: tag
    }).count()
    return {
      errCode: 0,
      errMsg: '成功',
      count: resourceres.total
    }
  } catch {
    return {
      errCode: 5000,
      errMsg: '内部错误',
      errFix: '联系客服'
    }
  }
}